<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./css/Carousel.css" />
  </head>
  <body>
    <div>
      <ul id="nav">
        <li class="active"></li>
        <li></li>
        <li></li>
        <li></li>
      </ul>
      <ul id="img">
        <div class="imgbox">
          <li class="active"><img src="./image/01.png" alt="" /></li>
          <li><img src="./image/02.png" alt="" /></li>
          <li><img src="./image/03.png" alt="" /></li>
          <li><img src="./image/04.png" alt="" /></li>
        </div>
      </ul>
    </div>
  </body>
  
  <script>
    var nav = document.getElementById("nav");
    var lis = nav.getElementsByTagName("li");
    var imgbox = document.getElementsByClassName("imgbox")[0];
    var ban = imgbox.getElementsByTagName("li");
    var time = null;
    var ind = 0;
    var imgW = ban[0].clientWidth;
    var imgboxW = imgbox.clientWidth;

    for (var i = 0; i < lis.length; i++) {
      lis[i].dataset.index = i;
      lis[i].onclick = function () {
        for (var j = 0; j < lis.length; j++) {
          lis[j].classList.remove("active");
        }
        this.classList.add("active");
        clearInterval(time);
        ind = this.dataset.index;
        timeChange();
        next_img();
      };
    }

    //定时切换
    function timeChange() {
      time = setInterval(function () {
        ind++;
        if (ind >= ban.length) {
          ind = 0;
        }
        for (var i = 0; i < lis.length; i++) {
          lis[i].classList.remove("active");
        }
        lis[ind].classList.add("active");
        next_img()
      }, 2000);
    }
    timeChange()

    //下一张切换
    function next_img() {
      var left = imgW * ind;
      if (left > imgboxW - imgW) {
        left = 0;
      }
      imgbox.style.left = -left + "px";
    }
  </script>
</html>
